/**
 * 判断输入类型
 * @param  { Object | Array }  obj 对象/数组
 * @return { Type }
 */
function typeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLocaleLowerCase();
}

/**
 * 获取前后 n 天的具体时间
 * @param  { Number }  day 前后 n 天
 * @return { Date } Fri Jul 28 2017 15:06:40 GMT+0800 (CST)
 */
function getDayOf(day) {
  day = parseInt(day);
  if (Number.isNaN(day)) return;

  let today = new Date();
  let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  return new Date(targetday_milliseconds);
}

// 获取前后 n 天的日期，0为今天
// retrun yyyy-mm-dd
function getDay(day) {
  var today = new Date();

  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;

  today.setTime(targetday_milliseconds); //注意，这行是关键代码

  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear + "-" + tMonth + "-" + tDate;
}

function doHandleMonth(month) {
  var m = month;
  if (month.toString().length == 1) {
    m = "0" + month;
  }
  return m;
}

//获取近7天
function get7days() {
  let dNow = new Date();
  let d7Ago = new Date(dNow.getTime() - 6 * 24 * 3600 * 1000);
  let dNowFormat = dNow.Format('yyyy-MM-dd');
  let d7AgoFormat = d7Ago.Format('yyyy-MM-dd');
  return [d7AgoFormat, dNowFormat];
}

/**
 * 用于日期选择器插件快捷选项 pickerOptions.shortcuts 的生成
 * @param  { Array }  所需快捷选项组成的数组（0表示今日，-1表示昨日）
 * @return { Array } [{text: 'xx日', onClick(picker){}}...]
 */
function pickerShortcutsFactory(arr = [-1, -7, -30]) {
  if (typeOf(arr) !== 'array') return;

  let resultArr = [];
  arr.forEach(num => {
    resultArr.push(shortcutFactory(num));
  });
  return resultArr;
}

/**
 * 用于日期选择器插件快捷选项 pickerOptions.shortcuts 的生成的辅助函数
 * 生成一个快捷选项对象
 * @param  { Number(>0) }  需要生成的捷选项日期（0表示今日，-1表示昨日）
 * @return { Object } {text: 'xx日', onClick(picker){}}...
 */
function shortcutFactory(num) {
  num = parseInt(num);
  if (Number.isNaN(num) || num > 0) return;

  let shortcutText = '';
  let pickEventParams = [];
  switch (num) {
    case 0:
      shortcutText = '今日';
      pickEventParams = getDayOf(0);
      break;
    case -1:
      shortcutText = '昨日';
      pickEventParams = [getDayOf(-1), getDayOf(0)]
      break;
    default:
      shortcutText = `近${-num}日`;
      pickEventParams = [getDayOf(num + 1), getDayOf(0)]
      break;
  }
  return {
    text: shortcutText,
    onClick(picker) {
      picker.$emit('pick', pickEventParams);
    }
  }
}



String.prototype.lengthB = function () {
  var s = this.replace(/[^\x00-\xff]/g, "**");
  return s.length;
}

Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
Date.prototype.Format = Date.prototype.format;

function isEmptyObject(e) {
  var t;
  for (t in e)
    return !1;
  return !0
}

//数字转为金融字符 例如 50000=>50,000
function numToLocal(num) {
  let re = Number(num).toLocaleString();
  re = isNaN(num) ? '/' : re;
  return re;
}

//数字转为缩略字符 例如 50000=>5万
function numToStr(num) {
  let re = '';
  num = num == "" ? 0 : num;
  if (num >= 100000000) {
    re = (num / 100000000).toFixed(2) + "亿";
  } else if (num >= 10000) {
    re = (num / 10000).toFixed(2) + "万";
  } else {
    re = num;
  }
  return re;
}


function dClick() {
  // 移除所有已激活detail按钮的active类名，
  // 如果已激活detail按钮里有图标，则换成 详情+向下图标
  var $activeDetail = $('.detail').filter('.active');
  $activeDetail.removeClass('active');
  if ($activeDetail.find('.fa').length > 0) {
    $activeDetail.html('详情<i class="fa fa-angle-down"></i>');
  }

  // 为detail-table添加消失动画,450ms为动画执行时间
  $activeDetail.next().addClass('flip-leave-active');
  setTimeout(function () {
    $activeDetail.next().hide();
    $activeDetail.next().removeClass('flip-leave-active');
  }, 450);
}

const dateRanges = {
  shortcuts: [{
    text: '最近一周',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit('pick', [start, end]);
    }
  }, {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit('pick', [start, end]);
    }
  }, {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      picker.$emit('pick', [start, end]);
    }
  }]
}
//   {
//     count: 0,
//     title: '今日'
//   },
//   {
//     count: 1,
//     title: '昨日'
//   },
//   {
//     count: 6,
//     title: '近七日'
//   },
//   {
//     count: 29,
//     title: '近30日'
//   }
// ]

/**
 * 参数序列化
 * @param  {[Object]} obj [需序列化的对象]
 * @return {[Stirng]}     [?key1=value1&key2=value2]
 */
function serialize(obj) {
  if (obj === null || typeof obj !== 'object') {
    return;
  }
  var url = '?';
  for (let key in obj) {
    var value = obj[key];
    if (value === '' || value == null) {
      value = '';
    }
    url = url + key + '=' + value + '&';
  }
  return url.slice(0, -1);
}

/**
 * 用于文件的导出
 * @param  { String }  url 导出地址
 * @return { File }
 */
function download_file(url) {
  if (typeof (download_file.iframe) == "undefined") {
    var iframe = document.createElement("iframe");
    download_file.iframe = iframe;
    document.body.appendChild(download_file.iframe);
  }
  download_file.iframe.src = url;
  download_file.iframe.style.display = "none";
  Shield.vMessage.warning('正在下载，请稍等...');
}
export {
  getDay,
  get7days,
  pickerShortcutsFactory,
  isEmptyObject,
  numToLocal,
  numToStr,
  dClick,
  dateRanges,
  serialize,
  download_file
};
